package org.fdy.common.framework.advice;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import lombok.extern.slf4j.Slf4j;
import org.fdy.common.core.enums.ResultCode;
import org.fdy.common.core.exception.BaseException;
import org.fdy.common.core.model.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>异常拦截</p>
 *
 * @author fangdayang
 * @date 2023-10-19 23:48
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<String> exception(Exception e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.error("请求地址'{}',系统异常", requestUri, e);
        return Result.fail(ResultCode.FAIL, "系统异常，请联系管理员");
    }


    /**
     * 业务异常信息处理
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result<String> baseException(BaseException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.warn("请求地址'{}',操作失败'{}'", requestUri, e.getMessage());
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 请求参数异常处理
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Result<String> paramExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        return doParamException(exceptions);
    }

    @ExceptionHandler({BindException.class})
    @ResponseBody
    public Result<String> bindExceptionHandler(BindException e) {
        BindingResult exceptions = e.getBindingResult();
        return doParamException(exceptions);
    }

    private Result<String> doParamException(BindingResult exceptions) {
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return Result.fail(ResultCode.REQUEST_PARAMS_ERROR.getCode(), fieldError.getDefaultMessage());
            }
        }
        return Result.fail(ResultCode.REQUEST_PARAMS_ERROR.getCode(), "");
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public Result<String> notLoginExceptionHandler(NotLoginException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.warn("请求地址'{}',认证失败,无法访问系统资源", requestUri);
        return Result.fail(ResultCode.NOT_LOGIN, "请先登录");
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseBody
    public Result<String> handleAccessDeniedException(NotPermissionException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.warn("请求地址'{}',权限校验失败", requestUri);
        return Result.fail(ResultCode.FAIL.getCode(), "没有权限，请联系管理员授权");
    }

    /**
     * 角色校验异常
     */
    @ExceptionHandler(NotRoleException.class)
    @ResponseBody
    public Result<String> handleAccessDeniedException(NotRoleException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.warn("请求地址'{}',角色校验失败", requestUri);
        return Result.fail(ResultCode.FAIL.getCode(), "没有角色，请联系管理员授权");
    }

}
